﻿


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Linq;
using Demo.Infrastructure;

using Demo.Web.UserService;
using Demo.Web.ModuleService;
using Demo.Web.ActionService;

namespace Demo.Web
{
    /// <summary>
    /// http请求用户上下文
    /// </summary>
    public class HttpUserContext
    {
        private static readonly UserServiceClient userClient = new UserServiceClient();

        private static readonly ModuleService.ModuleServiceClient moduleClient = new ModuleServiceClient();

        private static readonly ActionServiceClient actionClient = new ActionServiceClient();

        private UserDTO userInfo;
        private ActionDTO[] actions;
        private ModuleDTO[] modules;

        private HttpUserContext(UserDTO user)
        {
            this.userInfo = user;
        }

        /// <summary>
        /// 用户基本信息
        /// </summary>
        public UserDTO UserInfo {
            get
            {
                if (userInfo == null)
                {
                    var name = HttpContext.Current.User.Identity.Name;
                    var user = userClient.GetUserDTOWithName(name);
                    if (user != null)
                        userInfo = user;
                }
                return userInfo;
            } 
        }

        /// <summary>
        /// 用户行为集合
        /// </summary>
        public ActionDTO[] Actions
        {
            get
            {
                if (actions == null && UserInfo != null)
                {
                    actions = actionClient.GetActionDTOWithUserId(UserInfo.UserID);
                }
                return actions;
            }
        }

        /// <summary>
        /// 用户模块集合
        /// </summary>
        public ModuleDTO[] Modules
        {
            get
            {
                if (modules == null && UserInfo != null)
                {
                    modules = moduleClient.GetModuleDTOWithUserId(UserInfo.UserID);
                }
                return modules;
            }
        }

        /// <summary>
        /// 当前验证用户信息
        /// </summary>
        public static HttpUserContext Current
        {
            get
            {
                if (HttpContext.Current.User != null )
                {
                    var name = HttpContext.Current.User.Identity.Name;
                    var user = userClient.GetUserDTOWithName(name);
                    return new HttpUserContext(user);
                }
                return new HttpUserContext(null);
            }
        }
    }

}
